const express = require("express");
const {
  createItem,
  getAllItems,
  getItemById,
  updateItem,
  deleteItem,
  getItemSummaries,
  getItemsNearLocation,
  getRelatedItems,
  getTopTrendingItems,
  getLowStockItems,
  getItemsByCategory,
} = require("../controllers/itemController");
const { authMiddleware, hasPermission } = require("../middleware/authMiddleware");

const router = express.Router();

// Create item
router.post(
  "/items",
  authMiddleware,
  (req, res, next) => {
    if (req.user.role.toLowerCase() === "admin") return next();
    return hasPermission("Items", "Add")(req, res, next);
  },
  createItem
);

router.get(
  "/items",
  authMiddleware,
  (req, res, next) => {
    if (req.user.role.toLowerCase() === "admin") return next();
    return hasPermission("Items", "View")(req, res, next);
  },
  getAllItems
);

router.get(
  "/items/summary",
  authMiddleware,
  (req, res, next) => {
    if (req.user.role.toLowerCase() === "admin") return next();
    return hasPermission("Items", "View")(req, res, next);
  },
  getItemSummaries
);

router.get(
  "/items/near",
  authMiddleware,
  (req, res, next) => {
    
    if (req.user.role.toLowerCase() === "admin") return next();
    return hasPermission("Items", "View")(req, res, next);
  },
  getItemsNearLocation
);

router.get(
  "/items/top-trending",
  authMiddleware,
  (req, res, next) => {
    if (req.user.role.toLowerCase() === "admin") return next();
    return hasPermission("Items", "View")(req, res, next);
  },
  getTopTrendingItems
);

router.get(
  "/items/low-stock",
  authMiddleware,
  (req, res, next) => {
    if (req.user.role.toLowerCase() === "admin") return next();
    return hasPermission("Items", "View")(req, res, next);
  },
  getLowStockItems
);

router.get(
  "/items/category/:categoryId",
  authMiddleware,
  (req, res, next) => {
    if (req.user.role.toLowerCase() === "admin") return next();
    return hasPermission("Items", "View")(req, res, next);
  },
  getItemsByCategory
);

router.get(
  "/items/:id/related",
  authMiddleware,
  (req, res, next) => {
    if (req.user.role.toLowerCase() === "admin") return next();
    return hasPermission("Items", "View")(req, res, next);
  },
  getRelatedItems
);

// Get single item by ID
router.get(
  "/items/:id",
  authMiddleware,
  (req, res, next) => {
    if (req.user.role.toLowerCase() === "admin") return next();
    return hasPermission("Items", "View")(req, res, next);
  },
  getItemById
);

// Update item
router.put(
  "/items/:id",
  authMiddleware,
  (req, res, next) => {
    if (req.user.role.toLowerCase() === "admin") return next();
    return hasPermission("Items", "Edit")(req, res, next);
  },
  updateItem
);

// Delete item
router.delete(
  "/items/:id",
  authMiddleware,
  (req, res, next) => {
    if (req.user.role.toLowerCase() === "admin") return next();
    return hasPermission("Items", "Delete")(req, res, next);
  },
  deleteItem
);



module.exports = router;
